<?php
namespace Home\Controller\Mobile;
use Think\Controller;
/**
 * 公共类
 */
class BasicController extends Controller{
	public function __construct(){
		parent::__construct();

        /*$userarr = array(
            'uid'=>10,
        );
        session('user',$userarr);*/
       
       	$par['flag'] = 'system';
		$wxsz = M('sxkj_offline_data')->where($par)->find();
		$wxsz = json_decode($wxsz['data'],true);
		
		$jsxcode = I("request.jsxcode");
		$user = session('user');
		
		if($wxsz['login_type']!=2){
			if(empty($user)){				
				//判断是否微信端
				/*$ua = $_SERVER['HTTP_USER_AGENT']; 
				if(strpos($ua, 'MicroMessenger') === false && strpos($ua, 'Windows Phone') === false){
					echo '请在微信中打开';exit;
			  	}*/
		
	         	$appId = $wxsz['appid'];
				
				//获取当前网页，授权后跳回
	         	$path =  $_SERVER['REQUEST_URI'];
	          
	         	$redirect_uri = urlencode($this->get_http().'://'.$_SERVER['HTTP_HOST'].U('Home/Mobile/Auth/back',array('jsxcode'=>$jsxcode)));//授权成功返回地址
	
				//下面$url请求授权登录地址,此处为静默授权，scope可改成snsapi_userinfo，注意此URL不能换行,静默授权只能获取_token 和 openId
	         	$url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appId.'&redirect_uri='.$redirect_uri.'&response_type=code&scope=snsapi_userinfo&state='.$path.'#wechat_redirect';
	          	header('Location:'.$url);
	     	}
	     	
	     	if(!IS_AJAX){
				$wxdata = $this->getSignPackage($wxsz['appid']);
				$this->assign('wxdata',$wxdata);
			}
		}else{
			if(empty($user)){
				$url = $this->get_http().'://'.$_SERVER['HTTP_HOST'].U('Home/Mobile/Login/login',array('jsxcode'=>$jsxcode));
				header('Location:'.$url);
			}
		}
	}

    public function getSignPackage($appId) {
        $jsapiTicket = $this->getJsApiTicket();
		         
        $url = $this->get_http()."://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        $timestamp = time();
        $nonceStr = $this->createNonceStr();
        // 这里参数的顺序要按照 key 值 ASCII 码升序排序
        $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
        $signature = sha1($string);
        $signPackage = array(
            "appId" => $appId,
            "nonceStr" => $nonceStr,
            "timestamp" => $timestamp,
            "url" => $url,
            "signature" => $signature,
            "rawString" => $string
        );
        return $signPackage;
    }

    public function createNonceStr($length = 16){
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    public function getJsApiTicket(){   	
        $info = json_decode(file_get_contents("./php/wxpay/ticket/jsapi_ticket.json"),true);
        
		if($info['expires_in'] < time() || empty($info['jsapi_ticket']) ){			
			$accessToken = $this->getAccessToken();
			$url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=1&access_token=$accessToken";
			$obj = json_decode($this->httpGet($url));
			//失效重新获取token
			if($obj->errcode==40001 || $obj->errcode==42001){
				$accessToken = $this->refreshAccessToken();
				$url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=1&access_token=$accessToken";
				$obj = json_decode($this->httpGet($url));
			}
			if($obj){
				$arr['jsapi_ticket'] = $obj->ticket;	
				$arr['expires_in'] = time() + 7000; 
				
				$dir = './php/wxpay/ticket/';	
		    	// 判断目录是否存在
		    	if (!file_exists($dir)){
		    		// 创建目录
		     	   	mkdir($dir,0777,true);
		     	} 
				
				$fp = fopen("./php/wxpay/ticket/jsapi_ticket.json", "w");
        		fwrite($fp, json_encode($arr));
        		fclose($fp);
                return $obj->ticket;					
			}			
		}else{
			return $info['jsapi_ticket'];
		}	
    }
	
	//获取微信签名所需的access_token
    public function getAccessToken() {  
	    $par['flag'] = 'system';
		$wxsz = M('sxkj_offline_data')->where($par)->find();
		$wxsz = json_decode($wxsz['data'],true);
		
		$appId = $wxsz['appid'];
		$appSecret = $wxsz['appsecret']; 
    	     
       	$info = json_decode(file_get_contents("./php/wxpay/token/access_token.json"),true);       
		if($info['expires_in'] < time()  || empty($info['access_token']) ){ 
			$url_token = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appId.'&secret='.$appSecret;
            $tmp = $this->httpGet($url_token);
            $obj = json_decode($tmp);
            $accessToken = $obj->access_token;
		
			$arr['access_token'] = $accessToken;
			$arr['expires_in'] = time() + 7000;              
			
			$dir = './php/wxpay/token/';	
	    	// 判断目录是否存在
	    	if (!file_exists($dir)){
	    		// 创建目录
	     	   	mkdir($dir,0777,true);
	     	}               	
           	$fp = fopen("./php/wxpay/token/access_token.json", "w");
    		fwrite($fp, json_encode($arr));
    		fclose($fp);
			return $accessToken;
        }else{
			return $info['access_token'];
        }
    }
    
    //刷新微信签名所需的access_token    
    public function refreshAccessToken() {       
	    $par['flag'] = 'system';
		$wxsz = M('sxkj_offline_data')->where($par)->find();
		$wxsz = json_decode($wxsz['data'],true);
		
		$appId = $wxsz['appid'];
		$appSecret = $wxsz['appsecret'];   
		
		//获取token的值
		$url_token = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appId.'&secret='.$appSecret;
        $tmp = $this->httpGet($url_token);
        $obj = json_decode($tmp);
        $accessToken = $obj->access_token;

		$arr['access_token'] = $accessToken;
		$arr['expires_in'] = time() + 7000;              
						
		$dir = './php/wxpay/token/';	
		// 判断目录是否存在
		if (!file_exists($dir)){
			// 创建目录
			mkdir($dir,0777,true);
		}               	
		$fp = fopen("./php/wxpay/token/access_token.json", "w");
		fwrite($fp, json_encode($arr));
		fclose($fp);
		return $accessToken;
    }
    
    //随机数
   	public function getRandom($param){

	    $str="0123456789abcdefghijklmnopqrstuvwxyz";
	
	    $key = "";
	
	    for($i=0;$i<$param;$i++){
	        $key .= $str{mt_rand(0,32)};
	    }
		return $key;
	}
   	
   	public function get_http(){
		if($_SERVER['HTTPS'] === 1){  //Apache  
			$h = 'https';  
		}elseif($_SERVER['HTTPS'] === 'on'){ //IIS  
			$h = 'https'; 
		}elseif($_SERVER['SERVER_PORT'] == 443){ //其他  
			$h = 'https'; 
		}else{
			$h = 'http';
		}
		return $h;		
   	}
   	  
   	function xmlToArray($xml){ 
 
		$xml = str_replace('<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">', '', $xml);
		
		$xml = str_replace('</string>', '', $xml);		
		
		$xml = html_entity_decode($xml);
		
		libxml_disable_entity_loader(true); 
		 
		$xmlstring = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA); 
		 
		$val = json_decode(json_encode($xmlstring),true); 
		 
		return $val; 
			 
	} 
	
    public function getSign($key,$data){
        //签名步骤一：按字典序排序参数
        ksort($data);
        $string_a=http_build_query($data);
        $string_a=urldecode($string_a);
        //签名步骤二：在string后加入KEY
        $string_sign_temp=$string_a.$key;
        //签名步骤三：MD5加密
        $sign = md5($string_sign_temp);
        //签名步骤四：所有字符转为大写
        $result=strtoupper($sign);
        return $result;
    }
    
    public function curl($url){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        $data = curl_exec($curl);
        curl_close($curl);
        return $data;
    }
    
	public function httpGet($url){
	    if(function_exists('curl_init')){
	        $ch = curl_init();
	        curl_setopt($ch, CURLOPT_URL, $url);
	        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
	        curl_setopt($ch, CURLOPT_HEADER, 0);
	        $return = curl_exec($ch);
	        curl_close($ch); 
	        return $return;
	    }
	    return false;
	}
	
	public function dopost($url,$post_data,$headers=''){
	    $ch = curl_init();
	    curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		// post数据
		curl_setopt($ch, CURLOPT_POST, 1);
		// post的变量
		curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
		//不验证证书下同
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        if(!empty($headers)){
        	curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
        }
		$output = curl_exec($ch);
		curl_close($ch);
		return $output;
	} 
     
}